import random
import re
from datetime import datetime

from flask import abort, jsonify
from flask import current_app
from flask import make_response
from flask import request
from flask import session

from info import redis_store, constants, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue


@passport_blue.route('/image_code')
def image_code():
    # 批量删除固定前缀
    # r.delete(*r.keys('*test*'))
    try:
        redis_store.delete(*redis_store.keys('*image_code_id*'))
    except Exception as e:
        current_app.logger.error(e)
    image_code_id = request.args.get('image_code_id')
    if not image_code_id:
        return abort(403)
    name, text, image_data = captcha.generate_captcha()
    try:
        # redis_store = None # type:redis.StrictRedis

        redis_store.setex('image_code_id' + image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

    except Exception as e:
        current_app.logger.error(e)
        return make_response(jsonify(errno=RET.DATAERR, errmsg='验证码储存失败'))
    resp = make_response(image_data)
    resp.headers['Content-Type'] = 'image/jpg'
    return resp


@passport_blue.route('/sms_code', methods=['POST'])
def sms_code():
    param_dict = request.json
    mobile = param_dict.get('mobile')
    image_code = param_dict.get('image_code')
    image_code_id = param_dict.get('image_code_id')
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    if not re.match(r'^1[3-9][0-9]{9}$', mobile):
        return jsonify(errno=RET.DATAERR, errmasg='手机号不正确')
    try:
        real_image_code = redis_store.get('image_code_id' + image_code_id)
        if real_image_code:
            # 解码
            real_image_code = real_image_code.decode()
            # 删除储存的验证码图片
            redis_store.delete('image_code_id' + image_code_id)
    except  Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='图片验证码获取失败')
    if not real_image_code:
        # 验证码已经过期
        return jsonify(errno=RET.NODATA, errmsg='验证码过期')
    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg='验证码错误')
    # 检查是否重复注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='查询用户信息失败')
    if user:
        return jsonify(errno=RET.DATAERR, errmsg='用户已经注册')
    # 生成验证码
    num = random.randint(0, 999999)
    sms_code = '%06d' % num
    current_app.logger.info('短信验证码内容:%s' % sms_code)
    result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], 1)
    if result != '000000':
        # 发送短信失败
        return jsonify(errno=RET.THIRDERR, errmsg='发送短信失败')
    try:
        redis_store.setex('SMS_' + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存验证码失败')
    return jsonify(errno=RET.OK, errmsg='发送成功')


@passport_blue.route('/register', methods=['post'])
def register():
    json_data = request.json
    mobile = json_data.get('mobile')
    sms_code = json_data.get('sms_code')
    password = json_data.get('password')
    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    # 对比短信验证码
    try:
        real_sms_code = redis_store.get('SMS_' + mobile)
        print(real_sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取本地验证码失败')
    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg='短信验证码过期')
    if sms_code != real_sms_code.decode():
        return jsonify(errno=RET.DATAERR, errmsg='验证码错误')
    try:
        redis_store.delete('SMS_ ' + mobile)
    except Exception as e:
        current_app.logger.error(e)
    user = User()
    user.nick_name = mobile
    user.password = password
    user.mobile = mobile
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据保存错误')
    # 保持登陆状态
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name

    return jsonify(errno=RET.OK, errmsg="OK")


@passport_blue.route('/login', methods=['post'])
def login():
    json_data = request.json
    mobile = json_data.get('mobile')
    password = json_data.get('password')
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    # 查询用户
    if not user:
        return jsonify(errno=RET.DBERR, errmsg="用户不存在")
    # 检查密码
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DBERR, errmsg="密码错误")

    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile
    session['is_admin'] = user.is_admin
    user.last_login = datetime.now()
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
    return jsonify(errno=RET.OK, errmsg="OK")


@passport_blue.route('/logout', methods=['POST'])
def logout():
    """清除session"""
    session.pop('user_id', None)
    session.pop('nick_name', None)
    session.pop('mobile', None)
    session.pop('is_admin', None)
    return jsonify(errno=RET.OK, errmsg='ok')
